<?php

namespace app\api\controller;

use app\api\model\GradeNoble;
use app\api\model\GradeNobleTimes;
use app\api\model\User;
use app\api\model\OrderCommon;
use app\api\model\ConfigSystem as Config;
use app\api\model\UserNoble;
use app\api\model\VolleyDesc as Balance;
use app\api\model\Dymanic;
use app\api\model\Topup;
use think\Db;
use Vectorface\Whip\Whip;

class Order extends Common
{
    public function noble($w2 = 0)
    {
        $userlimit = Db::name('topup_limit')->where(['user_id'=>$this->member['id'], 'value'=>['>', 0]])->value('value');
        if($userlimit) {//限制购买
            return $this->miss('禁止购买vip');
        }
        $config = Config::index('', 'vip_bought');
        $vip_bought = $config['vip_bought'];
        if (!$vip_bought) {
            return $this->miss('暂未开放购买');
        }
        $gradeNobleTimes = GradeNobleTimes::get($this->params['id']);
        if (!$gradeNobleTimes) return $this->return['common.error.notExist'];

        $gradeNoble = GradeNoble::get($gradeNobleTimes->noble_id);

        if (!$gradeNoble) return $this->return['common.error.notExist'];

        $lastBuy = OrderCommon::where(['types'=>6,'user_id'=>$this->member['id'],'data'=>json_encode(['id' => $this->params['id']]),'status'=>1])->whereTime('create_time','-30 day')->find();
        if ($lastBuy) {
            return $this->miss('同一套餐30天内仅可购买一次');
        }

        if ($this->params['method'] == 1) {
            /*if ($gradeNobleTimes->price > $this->member['volley']) {
                return $this->return['user.error.insufficientBalance'];
            }

            $time = strtotime($this->member['noble_time']) > time() ? strtotime($this->member['noble_time']) : time();
            $time = strtotime($gradeNobleTimes->keep . ' ' . $gradeNobleTimes->times, $time);

            Balance::index($this->member['id'], $gradeNobleTimes->price, '开通贵族');
            OrderCommon::index(6, $this->member['id'], $gradeNobleTimes->price, $this->params['method'], json_encode(['id' => $this->params['id']]), 1);
            User::update(['id' => $this->member['id'], 'noble_grade' => $gradeNoble->grade, 'noble_time' => $time]);

            $userGrade = UserNoble::get(['user_id' => $this->member['id'], 'grade' => $gradeNoble->grade]);
            if ($userGrade) {
                $userNobleTime = $userGrade['expire'] > time() ? $userGrade['expire'] : time();
                $userNobleTime = strtotime($gradeNobleTimes->keep . ' ' . $gradeNobleTimes->times, $userNobleTime);

                UserNoble::update(['id' => $userGrade->id, 'expire' => $userNobleTime, 'update_time' => time()]);
            } else {
                $userNobleTime = strtotime($gradeNobleTimes->keep . ' ' . $gradeNobleTimes->times);
                UserNoble::create([
                    'user_id' => $this->member['id'],
                    'grade' => $gradeNoble->grade,
                    'expire' => $userNobleTime,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
            }

            return $this->return['common.success.default'];*/
        } else {
            // $config = Config::index('', 'rate');

            //$recharge = round($gradeNoble->price / $config['rate'], 2);

            $recharge = round($gradeNobleTimes->price, 2);
            // if($this->member['noble_time'] > time()){
            //     return $this->miss('VIP到期前不能重复购买');
            // }
            $order = OrderCommon::index(6, $this->member['id'], $gradeNobleTimes->price, $this->params['method'], json_encode(['id' => $this->params['id']]));

            if (isset($this->params['h5']) && $this->params['h5']) {
                //$action = 'api/Alipaywap/tradeAppPay';

                return $this->pass(['order_sn' => $order['order_sn'], 'url' => 'api/wap/pay']);
            } else {
                $action = $this->params['method'] == 3 ? 'api/Wechat2/app' : 'api/Alipay/tradeAppPay';
                if ($w2 && $action == 'api/Wechat/app') {
                    $action = 'api/Wechat2/app';
                }

            }

            if ($this->params['method'] == 3) {
                $trade_type = 'T_NATIVE';
            } else {
                $action = 'api/adapay/index';
                $trade_type = 'alipay';
                return action($action, ['order_sn' => $order['order_sn'], 'total_amount' => $gradeNobleTimes->price, 'trade_type'=>$trade_type]);
            }
            return action($action, ['order_sn' => $order['order_sn']]);
        }
    }
    
    public function video()
    {
        $shortVideo = Dymanic::get($this->params['video_id']);
    
        if (!$shortVideo) return $this->return['common.error.notExist'];
    
        $config = Config::where(['category' => ['in', ['system', 'shortvideo']]])->column('title, content');

        if (!$config['recharge_switch']) return $this->return['dymanic.error.NoCharge'];
        
        $price = $config['unified_price_switch'] ? $config['unified_price'] : $shortVideo['price'];
   
        if (!$price) return $this->return['dymanic.error.NoCharge'];
    
        if ($this->params['method'] == 1) {
            if ($price > $this->member['volley']) {
                return $this->return['user.error.insufficientBalance'];
            }

            if ($shortVideo['type'] == 3) {
                $msg = '短视频';
                $data = ['video' => changeUrl($shortVideo['video'])];
            } else {
                $msg = '图集';

                $images = explode(',', $shortVideo['masterimg']);

                foreach ($images as $key => $item) {
                    $images[$key] = changeUrl($item);
                }

                $data = ['images' => $images];
            }
        
            Balance::index($this->member['id'], $price, "{$msg}付费");
            OrderCommon::index(7, $this->member['id'], $price, $this->params['method'], json_encode(['video_id' => $this->params['video_id']]), 1);
            User::fencheng($shortVideo['userid'], $this->member['id'], $price, 'video', $msg);
        
            return $this->pass($data);
        } else {
            $recharge = round($price, 2);
        
            $order = OrderCommon::index(7, $this->member['id'], $price, $this->params['method'], json_encode(['video_id' => $this->params['video_id']]));
        
            if (isset($this->params['h5']) && $this->params['h5']) {
                return $this->pass(['order_sn' => $order['order_sn'], 'url' => 'api/wap/pay']);
            } else {
                $action = $this->params['method'] == 3 ? 'api/Wechat/app' : 'api/Alipay/tradeAppPay';
            }
        
            return action($action, ['order_sn' => $order['order_sn']]);
        }
    }

    public function paystate($out_trade_no)
    {

        $ip = (new Whip())->getValidIpAddress();
        $cachekey = 'paystate'.$ip;
        if (cache($cachekey)) return $this->pass(['state'=>0, 'err'=>'查询频繁']);
        cache($cachekey, $out_trade_no, 2);

        $state = -100;
        
        $data = (new Topup)->master()->where(['numbers' => $out_trade_no])->find();
        
        if ($data) {
            $state = $data['state'];
        }
        
        if ($state == -100) {
            $data = (new OrderCommon)->master()->where(['number' => $out_trade_no])->find();
            
            if ($data) {
                $state = $data['status'];
            }
        }

        if ($state == -100) {
            $data = Db::name('mall_order')->master()->where(['number' => $out_trade_no])->find();
            
            if ($data) {
                $state = $data['status'];
            }
        }
        
        if ($state == -100) {
            $data = Db::name('order_of_service')->master()->where(['number' => $out_trade_no])->find();
            
            if ($data) {
                $state = $data['paystate'];
            }
        }
        
        if ($state == -100) {
            $data = Db::name('user_flag')->master()->where(['number' => $out_trade_no])->find();
            
            if ($data) {
                $state = $data['paystate'];
            }
        }
        if ($state == -100) {
            $data = Db::name('user_address_red_packet')->master()->where(['number' => $out_trade_no, 'type' => 1])->find();
            
            if ($data) {
                $state = $data['paystate'];
            }
        }

        if ($state == -100) {
            $data = Db::name('order_of_addressgood')->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
            
            if ($data) {
                $state = $data['paystate'];
            }
        }

        if ($state == -100) {
            $data = Db::name('activity_join')->master()->where(['number' => $out_trade_no])->find();
            
            if ($data) {
                $state = $data['paystate'];
            }
        }

        if ($state == -100) {
            $data = Db::name('user_demand')->master()->where(['order_sn' => $out_trade_no])->find();
            
            if ($data) {
                $state = $data['pay_state'];
            }
        }

        if ($state == -100) {
            return $this->miss('订单不存在');
        }
        
        return $this->pass(['state' => $state]);
    }

    public function orderCount()
    {
        
        return $this->pass([]);
        
        $user_id = $this->member['id'];
        // $user_id = 20093684;
        $service['buy'] = Db::name('order_of_service')->where(['user_id'=>$user_id, 'paystate'=>1, 'state'=>0, 'status'=>['in', [0,1]]])->count();
        $service['sale'] = Db::name('order_of_service')->where(['shopowner'=>$user_id, 'paystate'=>1, 'state'=>0, 'status'=>0])->count();
        $service['count'] = $service['buy'] + $service['sale'];

        $active['join'] = Db::name('activity_join')->where(['user_id'=>$user_id, 'state'=>0, 'paystate'=>1])->count();
        $active['pub'] = Db::name('activity_offline')->alias('a')->join('activity_join b', 'a.id=b.active_id')->where(['a.user_id'=>$user_id, 'a.status'=>1, 'a.state'=>0, 'b.paystate'=>1])->group('a.id')->count();
        $active['count'] = $active['join'] + $active['pub'];

        $result = [
            'service' => $service,
            'active'  => $active,
        ];
        return $this->pass($result);
    }

    public function orderInfo()
    {
        $order_sn = input('order_sn');
        return json(action('api/Wechat/check', ['out_trade_no'=>$order_sn]));
    }
}
